class MemoryCache {
  static final MemoryCache _instance = MemoryCache._internal();
  factory MemoryCache() => _instance;
  MemoryCache._internal();

  final Map<String, _CacheEntry> _cache = {};

  T? get<T>(String key) {
    final entry = _cache[key];
    if (entry == null) return null;

    if (entry.isExpired) {
      _cache.remove(key);
      return null;
    }

    return entry.value as T?;
  }

  void set<T>(String key, T value,
      {Duration duration = const Duration(minutes: 30)}) {
    _cache[key] = _CacheEntry(
      value: value,
      expiryTime: DateTime.now().add(duration),
    );
  }

  void remove(String key) {
    _cache.remove(key);
  }

  void clear() {
    _cache.clear();
  }

  // 清理过期缓存
  void cleanup() {
    _cache.removeWhere((_, entry) => entry.isExpired);
  }
}

class _CacheEntry {
  final dynamic value;
  final DateTime expiryTime;

  _CacheEntry({required this.value, required this.expiryTime});

  bool get isExpired => DateTime.now().isAfter(expiryTime);
}
